﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LinkExtender
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            CopyHyperlinksButton.IsEnabled = false;
        }

        private void GenerateButton_Click(object sender, RoutedEventArgs e)
        {
            Clear();

            var hyperlink = HyperlinkTextBox.Text;

            if (Check())
            {
                GenerateLinks(hyperlink);
                CopyHyperlinksButton.IsEnabled = true;
            }

        }

        private void Clear()
        {
            TextBoxDocument.Blocks.Clear();
            CopyHyperlinksButton.IsEnabled = false;
        }
        private bool Check()
        {
            var check = true;

            try
            {
                var count = Convert.ToInt32(CountTextBox.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("The count value has not been set correctly.");
                check = false;
            }

            try
            {
                //var numerals = Convert.ToInt32(NumeralsTextBox.Text);
                var comboBoxItemContent = ((ComboBoxItem)NumeralsComboBox.SelectedItem).Content;
                var numerals = Convert.ToInt32(comboBoxItemContent);
            }
            catch (Exception)
            {
                MessageBox.Show("The numerals value has not been set correctly.");
                check = false;
            }

            if (!HyperlinkTextBox.Text.Contains("*number*"))
            {
                check = false;
                MessageBox.Show("The hyperlink does not contain the codeword *number*");
            }
            

            return check;
        }

        private void GenerateLinks(string hyperlink)
        {
            var document = TextBoxDocument;
            var blocks = document.Blocks;

            var count = Convert.ToInt32(CountTextBox.Text);
            count++;
            for (var i = 0; i < count; i++)
            {
                blocks.Add(CreateParagraph(hyperlink, i));
            }

        }

        private Paragraph CreateParagraph(string hyperlink, int index)
        {
            //var editHyperlink = hyperlink.Replace("*number*", string.Format("{0}",index));
            var editHyperlink = "";

            //var numerals = Convert.ToInt32(NumeralsTextBox.Text);
            var comboBoxItemContent = ((ComboBoxItem)NumeralsComboBox.SelectedItem).Content;
            var numerals = Convert.ToInt32(comboBoxItemContent);

            switch (numerals)
            {
                case 2: editHyperlink = Create2NumeralsHyperlink(hyperlink, index); break;
                case 3: editHyperlink = Create3NumeralsHyperlink(hyperlink, index); break;
                case 4: editHyperlink = Create4NumeralsHyperlink(hyperlink, index); break;
                default: editHyperlink = CreateDefaultHyperlink(hyperlink, index); break;
            }

            //if (index < 10)
            //{
            //    editHyperlink = hyperlink.Replace("*number*", string.Format("0{0}", index));
            //}
            //else
            //{
            //    editHyperlink = hyperlink.Replace("*number*", string.Format("{0}", index));
            //}


            var para = new Paragraph();
            para.LineHeight = 10;
            para.Inlines.Add(editHyperlink);

            return para;
        }


        private string CreateDefaultHyperlink(string hyperlink, int index)
        {
            return hyperlink.Replace("*number*", string.Format("{0}", index));
        }
        private string Create2NumeralsHyperlink(string hyperlink, int index)
        {
            if (index < 10)
            {
                return hyperlink.Replace("*number*", string.Format("0{0}", index));
            }
            else
            {
                return hyperlink.Replace("*number*", string.Format("{0}", index));
            }
        }
        private string Create3NumeralsHyperlink(string hyperlink, int index)
        {
            if (index < 10)
            {
                return hyperlink.Replace("*number*", string.Format("00{0}", index));
            }
            else if (index < 100)
            {
                return hyperlink.Replace("*number*", string.Format("0{0}", index));
            }
            else
            {
                return hyperlink.Replace("*number*", string.Format("{0}", index));
            }
        }

        private string Create4NumeralsHyperlink(string hyperlink, int index)
        {
            if (index < 10)
            {
                return hyperlink.Replace("*number*", string.Format("000{0}", index));
            }
            else if (index < 100)
            {
                return hyperlink.Replace("*number*", string.Format("00{0}", index));
            }
            else if (index < 1000)
            {
                return hyperlink.Replace("*number*", string.Format("0{0}", index));
            }
            else
            {
                return hyperlink.Replace("*number*", string.Format("{0}", index));
            }
        }

        private void CopyHyperlinks_Click(object sender, RoutedEventArgs e)
        {
            var links = TextBoxDocument.Blocks;
            StringBuilder sb = new StringBuilder();

            foreach (Paragraph para in links)
            {
                var line = ((Paragraph)para).Inlines.FirstOrDefault();
                var run = ((Run)line).Text;
                sb.AppendLine(run);
            }

            try
            {
                Clipboard.SetText(sb.ToString());
            }
            catch
            {
                
            }
        }

        private void SearchLinksButton_Click(object sender, RoutedEventArgs e)
        {
            TextBoxDocument.Blocks.Clear();

            var hyperlink = HyperlinkTextBox.Text;

            try
            {
                var htmlcode = getHTML(hyperlink);
                addImageLinksToTextBox(getImageLinks(htmlcode));

                CopyHyperlinksButton.IsEnabled = true;
            }
            catch
            {
                MessageBox.Show("The Hyperlink is not correct.");
            }

            

        }

        private void addImageLinksToTextBox(List<string> links)
        {
            var document = TextBoxDocument;
            var blocks = document.Blocks;

            foreach (var link in links)
            {
                var para = new Paragraph();
                para.LineHeight = 10;
                para.Inlines.Add(link);
                blocks.Add(para);
            }
        }

        private List<string> getImageLinks(string htmlcode)
        {
            var ImageUrls = new List<string>();

            var links = GetSubStrings(htmlcode, "//", ".jpg").ToList();


            foreach (var link in links)
            {
                var splited = link.Split('>');

                if (splited.Length == 1)
                {
                    ImageUrls.Add(splited.FirstOrDefault());
                }
                else
                {
                    var editedLinks = new List<string>();

                    foreach (var splitedText in splited)
                    {
                        var split = splitedText.Split('"');
                        var lengths = new List<Int32>();
                        foreach (var l in split)
                        {
                            lengths.Add(l.Length);
                        }
                        if (lengths.Count == 2)
                        {
                            if (lengths[0] > lengths[1])
                            {
                                editedLinks.Add(split.ElementAt(0));
                            }
                            else
                            {
                                editedLinks.Add(split.ElementAt(1));
                            }
                        }

                    }
                    for (var i = 0; i < editedLinks.Count; i++)
                    {
                        if (!editedLinks[i].Contains(".jpg"))
                        {
                            editedLinks.RemoveAt(i);
                        }
                    }
                    foreach (var item in editedLinks)
                    {
                        ImageUrls.Add(item);
                    }
                }
            }


            var final = new List<string>();

            final = RemoveDoubleListItems(ImageUrls);

            
            for (var i = 0; i < final.Count; i++)
            {
                if (final[i].StartsWith("//"))
                {
                    final[i] = string.Format("http:{0}", final[i]);
                }
            }

                return final;

        }

        public List<string> RemoveDoubleListItems(List<string> list)
        {
            var newList = new List<string>();
            var keys = new Dictionary<string, object>();

            foreach (string listItem in list)
            {
                if (!keys.ContainsKey(listItem))
                {
                    newList.Add(listItem);
                    keys.Add(listItem, null);
                }
            }
            return newList;
        }

        private IEnumerable<string> GetSubStrings(string input, string start, string end)
        {
            Regex r = new Regex(Regex.Escape(start) + "(.*?)" + Regex.Escape(end));
            MatchCollection matches = r.Matches(input);
            foreach (Match match in matches)
                yield return start+match.Groups[1].Value+end;
        }


        public string getHTML(string url)
        {
            //Create request for given url
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            //Create response-object
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            //Take response stream
            StreamReader sr = new StreamReader(response.GetResponseStream());

            //Read response stream (html code)
            string html = sr.ReadToEnd();

            //Close streamreader and response
            sr.Close();
            response.Close();

            //return source
            return html;

        }

    }
}
